package com.huanglejing.shanggou.activity

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v4.util.ArrayMap
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.PagerSnapHelper
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.adapter.ProListDetailAdapter
import com.huanglejing.shanggou.bean.GoodsListBean
import com.huanglejing.shanggou.bean.NewComeProBean
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.*
import com.huanglejing.shanggou.greendao.CacheGoodsBean
import com.huanglejing.shanggou.greendao.CacheGoodsBeanDao
import com.huanglejing.shanggou.helper.MyPagerSnapHelper
import com.huanglejing.shanggou.interfaces.ProListDetailContract.ProListDetailPresenter
import com.huanglejing.shanggou.interfaces.ProListDetailContract.ProListDetailView
import com.huanglejing.shanggou.presenterimpl.ProListDetailImpl
import com.huanglejing.shanggou.utils.*
import com.huanglejing.shanggou.view.ExpandAnimationPop
import com.jcodecraeer.xrecyclerview.HorArrowRefreshHeader
import com.jcodecraeer.xrecyclerview.XHoRecyclerView
import com.rtdl.dropdownmenu.TwoMenuHolder
import kotlinx.android.synthetic.main.activity_pro_list_detail.*
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

class ProListDetailActivity : AppBaseActivity<ProListDetailPresenter<ProListDetailView>, ProListDetailView>(), ProListDetailView, XHoRecyclerView.LoadingListener {
    private var mData: ArrayList<NewComeProBean>? = arrayListOf()
    private var mBundleData: ArrayList<NewComeProBean>? = null
    private var leftPosion = 0
    private var cacheLeftPosion = 0
    private var cacheRightPosion = 0
    private var bundleLeftPosion = 0
    private var rightPosion = 0
    private var bundleRightPosion = 0
    private var mDataLeft: ArrayList<GoodsListBean>? = arrayListOf()
    private var mDataRight: ArrayList<ArrayList<GoodsListBean>>? = arrayListOf()
    private var mNextAdapter: ProListDetailAdapter? = null
    private var categoryId = ""
    private var smoothPosition = 0
    private var isNeedBack = false
    private var loadMoreText = ""
    private var refreshTextText = ""
    private var isLoadMoreFinish = true
    private var isRefrsesh = false
    private var isComeplete = false
    private var isRefreshFinishComplete = true
    private var isBag = true
    private var isBox = false
    private val mEmptyView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_empty)
    }
    private val mErrorView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_error)
    }

    private var beginPosition = 0
    private var middlePosition = 0
    private var afterPosition = 0

    private val menu by lazy {
        TwoMenuHolder(this@ProListDetailActivity,
                getCacheGoodsImgs() ?: arrayListOf(),
                { t1, t2 ->
                }, { view, i, i1 ->
            leftPosion = i
            rightPosion = i1
            if (leftPosion == mDataLeft?.size?.minus(1)
                    && rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                isComeplete = true
            } else {
                isComeplete = false
            }
            categoryId = mDataRight?.getOrNull(i)?.getOrNull(i1)?.guid ?: ""
            mNextAdapter?.setCacheData(getCacheGoods()?.filter {
                it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
            })
            if (mBundleData != null) {
                showContent(mBundleData)
                mBundleData = null
            } else {
                mBasePresenter?.getProListDetail()
            }
            xr_toolbar_list?.scrollToPosition(0)
        })
    }
    private var myPop: ExpandAnimationPop? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        categoryId = intent?.extras?.getString("categoryId") ?: ""
        smoothPosition = intent?.extras?.getInt("position") ?: 0
        isNeedBack = intent?.extras?.getBoolean("isNeedBack", false) ?: false
        bundleLeftPosion = intent?.extras?.getInt("leftPosion") ?: 0
        bundleRightPosion = intent?.extras?.getInt("rightPosion") ?: 0
        val jsonStr = intent?.extras?.getString("mBundleData") ?: ""
        mBundleData = AppContext.gson()?.fromJson<ArrayList<NewComeProBean>>(jsonStr)
        initPop()
        initWidget()
    }

    override fun onResume() {
        super.onResume()
    }

    private fun initPop() {
        val mRootView = LayoutInflater.from(this@ProListDetailActivity).inflate(R.layout.layout_pro_detail_pop_background, null, false)
        mRootView?.findViewById<TextView>(R.id.tv_pop_bag)?.setOnClickListener {
            isBag = true
            isBox = false
//            mNextAdapter?.setProductsNum(true, mNextAdapter?.currentNum?.plus(mData?.get(clickPosition)?.bagCount?.toIntOrNull()
//                    ?: 0) ?: 0)
            insertBean(true)
        }
        mRootView?.findViewById<TextView>(R.id.tv_pop_box)?.setOnClickListener {
            isBag = false
            isBox = true
//            mNextAdapter?.setProductsNum(true, mNextAdapter?.currentNum?.plus(mData?.get(clickPosition)?.boxCount?.toIntOrNull()
//                    ?: 0) ?: 0)
            insertBean(true)
        }
        myPop = ExpandAnimationPop(this@ProListDetailActivity)
        val drawable = ColorDrawable(0x00000000)
        myPop?.setBackgroundDrawable(drawable)
        myPop?.setTouchable(true)
        //   mPop?.setFocusable(true)
        myPop?.setOutsideTouchable(true)
        myPop?.setContentView(mRootView)
        myPop?.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT)
        myPop?.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
    }

    private fun initWidget() {
        setAPPTitle("")
        iv_search?.setOnClickListener {
            UIHelper.startActivity(SearchActivity::class.java)
        }
        iv_buy_car?.setOnClickListener {
            val intent = Intent(this@ProListDetailActivity, CurrentOrderActivity::class.java)
            intent?.putExtra("requestCode", 400)
            startActivityForResult(intent, 400)
        }
        bt_my_title.setOnClickListener {
            menu.TopTapClick()
            if (menu.isMenuOpen) {
                val drawable = resources.getDrawable(R.drawable.ic_arrow_up)
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                bt_my_title.setCompoundDrawables(null, null, drawable, null)
            } else {
                val drawable = resources.getDrawable(R.drawable.ic_arrow_down_red)
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                bt_my_title.setCompoundDrawables(null, null, drawable, null)
            }
        }

        tv_pro_list_detail_pop?.setOnClickListener {
            if (myPop != null && myPop?.isShowing() === false) {
                val ints = unDisplayViewSize(myPop?.getContentView()
                        ?: View(this@ProListDetailActivity))
                Log.d("heigt", "heigt    " + ints[1])
                Log.d("heigt", "heigt    width " + ints[0])
                myPop?.showAsDropDown(it, 0, DisplayUtils.`$dp2px`(5f))


            }
        }
        tv_pro_list_detail_add?.setOnClickListener {
            //            mNextAdapter?.setProductsNum(true, mNextAdapter?.currentNum?.plus(mData?.get(clickPosition)?.bagCount?.toIntOrNull()
//                    ?: 0) ?: 0)
            isBag = true
            isBox = false
            insertBean(true)
        }
        tv_pro_list_detail_minus?.setOnClickListener {
            insertBean(false)
        }
        if (isNeedBack) {
            bt_my_title?.visibility = View.VISIBLE
            xr_toolbar_list?.setPullRefreshEnabled(true)
            xr_toolbar_list?.setLoadingMoreEnabled(true)
        } else {
            bt_my_title?.visibility = View.INVISIBLE
            xr_toolbar_list?.setPullRefreshEnabled(false)
            xr_toolbar_list?.setLoadingMoreEnabled(false)
        }

        xr_toolbar_list?.setLoadingListener(this)
        //设置加载风格
//        xr_toolbar_list?.setLoadingMoreProgressStyle(ProgressStyle.LineScale)
//        xr_toolbar_list?.setRefreshProgressStyle(ProgressStyle.BallGridPulse)
        xr_toolbar_list?.setDRAG_RATE(1.7f)

        val manager = LinearLayoutManager(this@ProListDetailActivity, LinearLayoutManager.HORIZONTAL, false)
        xr_toolbar_list?.layoutManager = manager
        manager?.findFirstVisibleItemPosition()
        // 将SnapHelper attach 到RecyclrView
        val snapHelper = MyPagerSnapHelper()
        snapHelper?.setOnPagerSnapListener {
            if (xr_toolbar_list?.isNoMore ?: false
                    && beginPosition == mData?.size
                    && middlePosition == mData?.size
                    && afterPosition == mData?.size?.minus(1)) {
                xr_toolbar_list?.scrollToPosition(beginPosition)
            }
        }
        snapHelper.attachToRecyclerView(xr_toolbar_list)
        mNextAdapter = ProListDetailAdapter(this@ProListDetailActivity, mData ?: arrayListOf())
        xr_toolbar_list?.adapter = mNextAdapter
        xr_toolbar_list?.getRefreshHeader()?.visibility = View.GONE
        xr_toolbar_list?.setOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

                if (1 == newState) {
                    beginPosition = manager?.findFirstVisibleItemPosition()
                } else if (2 == newState) {
                    middlePosition = manager?.findFirstVisibleItemPosition()
                } else if (0 == newState) {
                    afterPosition = manager?.findFirstVisibleItemPosition()
                }
            }
        })
    }

    private fun insertBean(isAdd: Boolean) {
        var clickPosition = (xr_toolbar_list?.layoutManager as? LinearLayoutManager)?.findFirstVisibleItemPosition()
                ?: 0
        val childView = (xr_toolbar_list?.layoutManager as? LinearLayoutManager)?.findViewByPosition(clickPosition)
        if (clickPosition == 0 && childView is HorArrowRefreshHeader) {
            clickPosition = 0
        } else {
            clickPosition = (xr_toolbar_list?.layoutManager as? LinearLayoutManager)?.findFirstVisibleItemPosition()?.minus(xr_toolbar_list?.headViewCount
                    ?: 0) ?: 0
        }
        var loadAll = getCacheGoods()?.filter {
            it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
        }
        var isUpdate = false
        var updateBean: CacheGoodsBean? = null
        loadAll?.forEachIndexed { index, orderBean ->
            if (orderBean?.goodNO?.equals(mData?.get(clickPosition)?.id ?: "") ?: false) {
                isUpdate = true
                updateBean = orderBean
            }
        }
        var numAfter = updateBean?.num?.toIntOrNull() ?: 0

        if (isAdd && isBag && !isBox
                && numAfter < (mData?.get(clickPosition)?.count?.toIntOrNull() ?: 0)) {

            numAfter = numAfter?.plus(1)
            if (numAfter > (mData?.get(clickPosition)?.count?.toIntOrNull()
                            ?: 0) || numAfter == (mData?.get(clickPosition)?.count?.toIntOrNull()
                            ?: 0)) {
                ToastUtils.toastLong("${AppContext.get().resources.getString(R.string.str_maxmun_to_buy)}${mData?.get(clickPosition)?.count}")
                numAfter = mData?.get(clickPosition)?.count?.toIntOrNull() ?: 0
            }
        } else if (isAdd && !isBag && isBox
                && numAfter < (mData?.get(clickPosition)?.count?.toIntOrNull() ?: 0)) {
            numAfter = numAfter?.plus(mData?.get(clickPosition)?.boxCount?.toIntOrNull()?.div(mData?.get(clickPosition)?.bagCount?.toIntOrNull()
                    ?: 1) ?: 1)
            if (numAfter > (mData?.get(clickPosition)?.count?.toIntOrNull() ?: 0) ||
                    numAfter == (mData?.get(clickPosition)?.count?.toIntOrNull() ?: 0)) {
                ToastUtils.toastLong("${AppContext.get().resources.getString(R.string.str_maxmun_to_buy)}${mData?.get(clickPosition)?.count}")
                numAfter = mData?.get(clickPosition)?.count?.toIntOrNull() ?: 0
            }
        } else if (!isAdd && isBag && !isBox && numAfter > 0) {
            numAfter = numAfter?.minus(1)
        } else if (!isAdd && !isBag && isBox && numAfter > 0) {
            numAfter = numAfter?.minus(mData?.get(clickPosition)?.boxCount?.toIntOrNull()?.div(mData?.get(clickPosition)?.bagCount?.toIntOrNull()
                    ?: 1) ?: 1)
        }
        if (numAfter < 0) {
            numAfter = 0
        }
        if (isUpdate && updateBean != null && numAfter > 0) {
            updateBean?.goodNO = mData?.get(clickPosition)?.id ?: ""
            updateBean?.companyId = AppContext.get()?.companyId ?: ""
            updateBean?.customerId = CacheCustomerId ?: ""
            updateBean?.bz = updateBean?.bz ?: ""
            updateBean?.categoryGUID = categoryId ?: ""
            updateBean?.num = numAfter?.toString() ?: "0"
            updateBean?.price = mData?.get(clickPosition)?.price ?: ""
            updateBean?.bagCount = mData?.get(clickPosition)?.bagCount ?: ""
            updateBean?.boxCount = mData?.get(clickPosition)?.boxCount ?: ""
            updateBean?.count = mData?.get(clickPosition)?.count ?: ""
            updateBean?.name = mData?.get(clickPosition)?.name ?: ""
            updateBean?.no = mData?.get(clickPosition)?.no ?: ""
            updateBean?.parentGuid = mData?.get(clickPosition)?.parentGuid ?: ""
            updateBean?.url = mData?.get(clickPosition)?.url ?: ""
            updateBean?.xname = mData?.get(clickPosition)?.xname ?: ""
            updateBean?.zk = mData?.get(clickPosition)?.zk ?: ""
            val zhekou = mData?.get(clickPosition)?.zk?.toDoubleOrNull()?.div(100) ?: 0.00
            updateBean?.totalPrice = mData?.get(clickPosition)?.price?.toDoubleOrNull()?.times(numAfter
                    ?: 0)?.times(mData?.get(clickPosition)?.bagCount?.toIntOrNull()
                    ?: 1)?.times(1.minus(zhekou))?.toString() ?: ""
            beanDao?.update(updateBean)
        } else if (!isUpdate && updateBean == null && numAfter > 0) {
            updateBean = CacheGoodsBean()
            updateBean?.goodNO = mData?.get(clickPosition)?.id ?: ""
            updateBean?.companyId = AppContext.get()?.companyId ?: ""
            updateBean?.customerId = CacheCustomerId ?: ""
            updateBean?.bz = ""
            updateBean?.categoryGUID = categoryId ?: ""
            updateBean?.num = numAfter?.toString() ?: "0"
            updateBean?.price = mData?.get(clickPosition)?.price ?: ""
            updateBean?.bagCount = mData?.get(clickPosition)?.bagCount ?: ""
            updateBean?.boxCount = mData?.get(clickPosition)?.boxCount ?: ""
            updateBean?.count = mData?.get(clickPosition)?.count ?: ""
            updateBean?.name = mData?.get(clickPosition)?.name ?: ""
            updateBean?.no = mData?.get(clickPosition)?.no ?: ""
            updateBean?.parentGuid = mData?.get(clickPosition)?.parentGuid ?: ""
            updateBean?.url = mData?.get(clickPosition)?.url ?: ""
            updateBean?.xname = mData?.get(clickPosition)?.xname ?: ""
            updateBean?.zk = mData?.get(clickPosition)?.zk ?: ""
            val zhekou = mData?.get(clickPosition)?.zk?.toDoubleOrNull()?.div(100) ?: 0.00
            updateBean?.totalPrice = mData?.get(clickPosition)?.price?.toDoubleOrNull()?.times(numAfter
                    ?: 0)?.times(mData?.get(clickPosition)?.bagCount?.toIntOrNull()
                    ?: 1)?.times(1.minus(zhekou))?.toString() ?: ""
            beanDao?.insert(updateBean)
        } else if (isUpdate && updateBean != null && numAfter == 0) {
            beanDao?.delete(updateBean)
        }
        Observable.just(getCacheGoods())?.doOnNext {
            it?.filter {
                it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
            }
        }?.subscribeOn(Schedulers.io()) // Be notified on the main thread
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribe {
                    mNextAdapter?.setCacheData(it)
                    // (xr_toolbar_list?.layoutManager as? LinearLayoutManager)?.findViewByPosition(clickPosition)?.findViewById<TextView>(R.id.tv_product_list_detail_num)?.setText("$numAfter")
                    mNextAdapter?.notifyDataSetChanged()
                }?.addTo(rxManager);//这里的观察者依然不重要


    }

    override fun createPresenter(): ProListDetailPresenter<ProListDetailView> = ProListDetailImpl()

    override fun getLayoutId(): Int = R.layout.activity_pro_list_detail

    override fun requestPermission() {
    }

    override fun getProListDetailParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("companyId", AppContext.get().companyId)
            put("categoryId", categoryId)
        }
        return Observable.just(map)
    }

    override fun showGoodsList(data: ArrayList<GoodsListBean>) {
        mDataLeft?.clear()
        data.forEach {
            var list: ArrayList<GoodsListBean>? = null
            if (it.level == 0) {
                list = arrayListOf()
                mDataLeft?.add(it)
                mDataRight?.add(list)
            } else if (it.level == 1) {
                mDataRight?.getOrNull(mDataRight?.size?.minus(1) ?: 0)?.add(it)
            }
        }
        menu?.setOnMenuCloseListerner {
            val drawable = resources.getDrawable(R.drawable.ic_arrow_down_red)
            /// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            bt_my_title.setCompoundDrawables(null, null, drawable, null)
        }
        menu.isAutoRefresh = false
        menu.setDifideView(bt_my_title)
        menu.setMenuData(mDataLeft?.map { it.name ?: "" } as? ArrayList<String>
                ?: arrayListOf<String>(), mDataRight?.map {
            val list = it.map { it.name }
            return@map list as? ArrayList<String>
        } as? ArrayList<ArrayList<String>> ?: arrayListOf<ArrayList<String>>())

        ll_product_list_container.removeAllViews()
        ll_product_list_container.addView(menu.dropMenu)
        menu.setTopTapHide()
        menu?.outsideMenuClick(bundleLeftPosion, bundleRightPosion)
    }

    override fun <T> showContent(data: T?) {
        try {
            if (data as? ArrayList<NewComeProBean> != null) {
                isRefreshFinishComplete = true
                isLoadMoreFinish = true
                mData?.clear()
                mData?.addAll((data as? ArrayList<NewComeProBean>) ?: arrayListOf())
                if (mData?.size ?: 0 < 1 && mEmptyView != null) {
                    xr_toolbar_list?.emptyView = mEmptyView
                }
                mNextAdapter?.setData(mData)
                loadComPlete()
                getRefreshText()
                getLoadMoreText()
                xr_toolbar_list?.getRefreshHeader()?.visibility = View.VISIBLE
            }
        } catch (e: Exception) {
            KLog.e(e.message)
        }
    }

    private fun getLoadMoreText() {
        var tempLeft = 0
        var tempRight = 0
        if (leftPosion == mDataLeft?.size?.minus(1)) {
            if (rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                tempLeft = mDataLeft?.size?.minus(1) ?: 0
                tempRight = mDataRight?.getOrNull(leftPosion)?.size?.minus(1) ?: 0
            } else {
                tempLeft = mDataLeft?.size?.minus(1) ?: 0
                tempRight = rightPosion.plus(1)
            }
        } else {
            if (rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                tempLeft = leftPosion.plus(1)
                tempRight = 0
            } else {
                tempLeft = leftPosion
                tempRight = rightPosion.plus(1)

            }
        }
        if (leftPosion == mDataLeft?.size?.minus(1) ?: 0 && rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1) ?: 0) {
            loadMoreText = resources.getString(R.string.str_there_no_data_more)
        } else {
            loadMoreText = mDataRight?.getOrNull(tempLeft)?.getOrNull(tempRight)?.name ?: mDataLeft?.getOrNull(tempLeft)?.name ?: ""
        }
        xr_toolbar_list?.setLoadingMoreText(loadMoreText
                ?: resources.getString(R.string.str_up_slide_load), resources.getString(R.string.str_there_no_data_more), resources.getString(R.string.str_loading_more))
    }

    private fun getRefreshText() {
        var tempLeft = 0
        var tempRight = 0
        if (leftPosion == 0) {
            if (rightPosion == 0) {
                tempLeft = 0
                tempRight = 0
            } else {
                tempLeft = 0
                tempRight = rightPosion.minus(1)
            }
        } else {
            if (rightPosion == 0) {
                tempLeft = leftPosion.minus(1)
                tempRight = mDataRight?.getOrNull(tempLeft)?.size?.minus(1) ?: 0
            } else {
                tempLeft = leftPosion
                tempRight = rightPosion.minus(1)

            }

        }
        if (leftPosion == 0 && rightPosion == 0) {
            refreshTextText = resources.getString(R.string.str_there_no_data_more)
        } else {
            refreshTextText = mDataRight?.getOrNull(tempLeft)?.getOrNull(tempRight)?.name ?: mDataLeft?.getOrNull(tempLeft)?.name ?: ""

        }
        xr_toolbar_list?.setRefreshText(refreshTextText
                ?: resources.getString(R.string.str_down_slide_load), refreshTextText
                ?: resources.getString(R.string.str_release_and_refresh_immediately), resources.getString(R.string.str_refreshing), resources.getString(R.string.str_load_complete))


    }

    override fun showError(e: Throwable?) {
        isRefreshFinishComplete = true
        isLoadMoreFinish = true
        KLog.e(e?.message)
        if (mErrorView != null) {
            xr_toolbar_list?.emptyView = mErrorView
            mErrorView?.setOnClickListener {
                mBasePresenter?.getProListDetail()
            }
        }
        mNextAdapter?.setData(arrayListOf())
        loadComPlete()
    }

    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("companyId", AppContext.get().companyId)
        }
        return Observable.just(map)
    }

    override fun onRefresh() {
        cacheLeftPosion = leftPosion
        cacheRightPosion = rightPosion
        isComeplete = false
        isRefrsesh = true
        var loadAll = getCacheGoods()?.filter {
            it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
        }
        mNextAdapter?.setCacheData(loadAll)
        if (leftPosion == 0 && rightPosion == 0) {
            loadComPlete()
            return
        }
        if (isRefreshFinishComplete) {
            if (leftPosion == 0 && rightPosion != 0) {
                leftPosion = 0
                rightPosion = rightPosion.minus(1)
            } else {
                if (rightPosion == 0) {
                    leftPosion = leftPosion.minus(1)
                    rightPosion = mDataRight?.getOrNull(leftPosion)?.size?.minus(1) ?: 0
                } else {
                    leftPosion = leftPosion
                    rightPosion = rightPosion.minus(1)

                }
            }
            categoryId = mDataRight?.getOrNull(leftPosion)?.getOrNull(rightPosion)?.guid ?: ""

            menu.outsideMenuClick(leftPosion, rightPosion)
            /*  if (leftPosion == 0 && rightPosion == 0) {
                  loadComPlete()
                  return
              } else {
                  categoryId = mDataRight?.getOrNull(leftPosion)?.getOrNull(rightPosion)?.guid ?: ""

                  menu.outsideMenuClick(leftPosion, rightPosion)
              }*/
        }
        //    mBasePresenter?.getProductList()
    }

    override fun onLoadMore() {
//        var findFirstVisibleItemPosition = (xr_toolbar_list?.layoutManager as? LinearLayoutManager)?.findFirstVisibleItemPosition()
//        ToastUtils.toastLong("当前是${findFirstVisibleItemPosition}   总共${mNextAdapter?.itemCount}")
//        if (findFirstVisibleItemPosition ?: 0 <= mNextAdapter?.itemCount ?: 0) {
//            return
//        }
        cacheLeftPosion = leftPosion
        cacheRightPosion = rightPosion
        var loadAll = getCacheGoods()?.filter {
            it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
        }
        mNextAdapter?.setCacheData(loadAll)
        if (isLoadMoreFinish) {
            if (leftPosion == mDataLeft?.size?.minus(1)) {
                if (rightPosion != mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                    leftPosion = mDataLeft?.size?.minus(1) ?: 0
                    rightPosion = rightPosion.plus(1)
                    isComeplete = false
                } else {
                    isComeplete = true
                    loadComPlete()
                    return
                }
            } else {
                isComeplete = false
                if (rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                    leftPosion = leftPosion.plus(1)
                    rightPosion = 0
                } else {
                    leftPosion = leftPosion
                    rightPosion = rightPosion.plus(1)

                }
            }
            categoryId = mDataRight?.getOrNull(leftPosion)?.getOrNull(rightPosion)?.guid ?: ""
            isLoadMoreFinish = false
            menu.outsideMenuClick(leftPosion, rightPosion)

        }
        //   mBasePresenter?.getProductList()
    }

    fun loadComPlete() {
        xr_toolbar_list?.loadMoreComplete()
        xr_toolbar_list?.refreshComplete()
        if (!isComeplete) {
            xr_toolbar_list?.setNoMore(false)
        } else {
            xr_toolbar_list?.setNoMore(true)
        }
        if (isRefrsesh) {
            if (cacheLeftPosion != 0 || cacheRightPosion != 0) {
                xr_toolbar_list?.scrollToPosition(mNextAdapter?.itemCount?.minus(1) ?: 0)
            }
            isRefrsesh = false
        }/* else {
            xr_toolbar_list?.smoothScrollToPosition(0)
        }*/
        cacheLeftPosion = leftPosion
        cacheRightPosion = rightPosion
        if (smoothPosition != 0) {
            xr_toolbar_list?.scrollToPosition(smoothPosition?.plus(xr_toolbar_list?.headViewCount
                    ?: 0))
            smoothPosition = 0
        }
    }

    override fun finish() {
        if (isNeedBack) {
            val intent = Intent(this@ProListDetailActivity, ProductListActivity::class.java)
            val bundle = Bundle()
            bundle.putInt("leftPosion", leftPosion)
            bundle.putInt("rightPosion", rightPosion)
            bundle.putString("isBackData", AppContext.gson().toJson(mData))
            intent.putExtras(bundle)
            setResult(200, intent)
        }
        super.finish()
    }

    /*   fun loadComPlete() {
           xr_toolbar_list?.loadMoreComplete()
           xr_toolbar_list?.refreshComplete()
           if (!isComeplete) {
               xr_toolbar_list?.setNoMore(false)
           } else {
               xr_toolbar_list?.setNoMore(true)
           }
           if (smoothPosition!=0) {
               xr_toolbar_list?.smoothScrollToPosition(smoothPosition?.plus(xr_toolbar_list?.headViewCount
                       ?: 0))
               smoothPosition = 0
           } else {
               xr_toolbar_list?.smoothScrollToPosition(0)
           }
       }*/
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 400 && resultCode == 500) {
            mNextAdapter?.setCacheData(getCacheGoods()?.filter {
                it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
            })
            mNextAdapter?.notifyDataSetChanged()
        }
    }
}
